package com.lc.sell.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lc.sell.entity.User;
import com.lc.sell.mapper.UserMapper;
import com.lc.sell.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lc.sell.util.IdGenerator;
import com.lc.sell.util.TimeUtils;
import com.lc.sell.vo.ResultVo;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;
import sun.security.rsa.RSASignature;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 龙晨
 * @since 2022-02-15 02:21:17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultVo insertIntoUser(User user) {
        user.setCustomerId(IdGenerator.UidGenerator());
        user.setOpeningCardDate(TimeUtils.getNowDate());
        user.setBalance(new BigDecimal(0));
        userMapper.insert(user);
        return ResultVo.ok("添加成功!");
    }

    @Override
    public ResultVo findUserByPhoneAndPassword(HttpServletRequest request,String phone, String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("mobilePhone", phone).and(i -> i.eq("password", password)));
        if (user != null){
            request.getSession().setAttribute("userid",user.getCustomerId());
            user.setPassword(null);
            return ResultVo.ok("登录成功",user);
        }
        return ResultVo.fail("用户名或密码错误");
    }

    @Override
    public ResultVo updUser(User user) {
        BigDecimal balance = user.getBalance();
        User user1 = userMapper.selectById(user.getCustomerId());
        String balance1 = String.valueOf(user1.getBalance());
        BigDecimal add = null;
        if (balance != null){
            add = balance.add(new BigDecimal(balance1));
            user.setBalance(add);
        }

        int customerId = userMapper.update(user, new QueryWrapper<User>().eq("customerId", user.getCustomerId()));
        if (customerId>0){
            return ResultVo.ok("修改成功",add);
        }
        return ResultVo.ok("修改成功",customerId);
    }

    @Override
    public ResultVo selUserManey(String userid) {
        User user = userMapper.selectById(userid);
        return ResultVo.ok("查询成功",user.getBalance());
    }

    @Override
    public ResultVo selectOneUser(String userid) {
        User user = userMapper.selectById(userid);
        user.setPassword(null);
        return ResultVo.ok("查询成功",user);
    }
}
